package com.leesche.zcsp.node.app.v1.controller.operate;

import com.leesche.zcsp.node.app.v1.controller.admin.AppAdminController;
import com.leesche.zcsp.node.utils.UUIDGenerateUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.WebUtils;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.PubDevGiftStock;
import com.leesche.zcsp.node.web.service.PubDevGiftStockService;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDevGiftStockDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDevGiftStockCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * Created by kaider on 2016/11/18.
 * 礼品库存
 */
@Controller
@RequestMapping("/app/v1/operate/giftInventory")
public class AppGiftInventoryController extends AppAdminController {
    private final static Logger LOGGER = LoggerFactory.getLogger(AppGiftInventoryController.class);

    @Autowired
    private PubDevGiftStockService giftStockService;

    /**
     * 设备礼品库存列表
     * @param giftStockCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/giftListView", method = RequestMethod.POST)
    public Map<String,Object> giftListView(
            QueryPubDevGiftStockCondition giftStockCondition
    ){
        try {
//            Long adminId = 1L;
            Long adminId = getAdminId();
            giftStockCondition.setAdminId(adminId);
            List<PubDevGiftStockDto> giftStockDtoList = giftStockService.findListsByCondition(giftStockCondition);
            return WebResult.success().put("data",giftStockDtoList).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备添加礼品
     * @param devGiftStock
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Map<String, Object> uploadDeviceImage(
            PubDevGiftStock devGiftStock,
            @RequestParam(value = "uploadFile", required = false) MultipartFile image
    ) {
        try {
            if (image.isEmpty()) {
                return WebResult.failure("请选择礼品图片").toMap();
            }

            String fileName = image.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf("."));

            if (!WebUtils.checkIsImage(extName)
                    && !image.getContentType().matches("image.*")) {
                return WebResult.failure("上传的文件必须是图片!").toMap();
            }

            String hexString = WebUtils.getFileHexString(image.getInputStream());

            boolean flag = false;
            String[] magic = Constants.SYSTEM_IMAGE_MAGICNUMBER;
            for (int i = 0; i < magic.length; i++) {
                if (magic[i].equals(hexString)) {
                    flag = true;
                    break;
                }
            }

            if (flag == false) {
                return WebResult.failure("上传的文件类型不是图片,亲~别想忽悠我们哦。").toMap();
            }

            if (image.getSize() > Constants.SYSTEM_IMAGE_SIZE) {
                return WebResult.failure("上传的图片实在是太大了。不能超过" + Constants.SYSTEM_IMAGE_SIZE + "M哦~~").toMap();
            }

            String imagePath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_DEVICE_GIFT_DIRECTORY);
            String imageName = UUIDGenerateUtil.generateUUID() + extName;

            File imageFile = new File(imagePath, imageName);

            if (!imageFile.exists()) {
                imageFile.mkdirs();
            }

            image.transferTo(imageFile);
            Long adminId = getAdminId();
            devGiftStock.setAdminid(adminId);
            devGiftStock.setGiftimgurl(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_GIFT_DIRECTORY + "/" + imageName);
            giftStockService.insert(devGiftStock);
            return WebResult.success().put("data", devGiftStock.getGiftimgurl()).toMap();

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure("上传的图片无法识别。").toMap();
        }
    }

    /**
     * 设备单个礼品界面
     * @param devGiftStockCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editView", method = RequestMethod.POST)
    public Map<String,Object> editView(
            QueryPubDevGiftStockCondition devGiftStockCondition
    ){
        try {
            PubDevGiftStockDto devGiftStockDto = giftStockService.findByCondition(devGiftStockCondition);
            return WebResult.success().put("data",devGiftStockDto).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 修改设备单个礼品名称或数量
     * @param deviceId
     * @param devGiftStock
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editNameAndNum", method = RequestMethod.POST)
    public Map<String,Object> editNameAndNum(
            Long deviceId,
            PubDevGiftStock devGiftStock
    ){
        try {
            devGiftStock.setDeviceid(deviceId);
            giftStockService.updateByPrimaryKeySelective(devGiftStock);
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure("修改失败").toMap();
        }
    }

    /**
     * 修改设备单个礼品图片
     * @param devGiftStock
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Map<String,Object> edit(
            Long deviceId,
            PubDevGiftStock devGiftStock,
            @RequestParam(value = "uploadFile", required = false) MultipartFile image
    ){
        try {
            if (!image.isEmpty()) {
                String fileName = image.getOriginalFilename();
                String extName = fileName.substring(fileName.lastIndexOf("."));

                if (!WebUtils.checkIsImage(extName)
                        && !image.getContentType().matches("image.*")) {
                    return WebResult.failure("上传的文件必须是图片!").toMap();
                }

                String hexString = WebUtils.getFileHexString(image.getInputStream());

                boolean flag = false;
                String[] magic = Constants.SYSTEM_IMAGE_MAGICNUMBER;
                for (int i = 0; i < magic.length; i++) {
                    if (magic[i].equals(hexString)) {
                        flag = true;
                        break;
                    }
                }

                if (flag == false) {
                    return WebResult.failure("上传的文件类型不是图片,亲~别想忽悠我们哦。").toMap();
                }

                if (image.getSize() > Constants.SYSTEM_IMAGE_SIZE) {
                    return WebResult.failure("上传的图片实在是太大了。不能超过" + Constants.SYSTEM_IMAGE_SIZE + "M哦~~").toMap();
                }

                String imagePath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_DEVICE_GIFT_DIRECTORY);
                String imageName = UUIDGenerateUtil.generateUUID() + extName;

                File imageFile = new File(imagePath, imageName);

                if (!imageFile.exists()) {
                    imageFile.mkdirs();
                }

                image.transferTo(imageFile);
                devGiftStock.setGiftimgurl(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_DEVICE_GIFT_DIRECTORY + "/" + imageName);
            }

            devGiftStock.setDeviceid(deviceId);
            giftStockService.updateByPrimaryKeySelective(devGiftStock);
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure("上传的图片无法识别。").toMap();
        }
    }

}
